public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */

    //先反转链表

    private static ListNode reverse(ListNode head){

        if(head==null){
            return head;
        }

        ListNode cur=head;
        ListNode pre=null;
        while(cur!=null){
            ListNode temp=cur.next;
            cur.next=pre;
            //让前驱结点和当前结点都走一步
            pre=cur;
            cur=temp;
        }
        return pre;//反转链表最后返回的是pre,因为cur最后已经为null
    }

    //两条链表对应的数相加
    public ListNode addInList (ListNode head1, ListNode head2) {

        ListNode l1=reverse(head1);
        ListNode l2=reverse(head2);


        ListNode node=new ListNode(0);
        ListNode cur=node;
        int carry=0;
        while(l1!=null||l2!=null||carry!=0){

            int l1Val=(l1==null?0:l1.val);
            int l2Val=(l2==null?0:l2.val);

            int sum=l1Val+l2Val+carry;
            int num=sum%10;
            carry=sum/10;

            ListNode ansNode=new ListNode(num);
            cur.next=ansNode;
            cur=ansNode;

            if(l1!=null){
                l1=l1.next;
            }
            if(l2!=null){
                l2=l2.next;
            }
        }

        ListNode ans=node.next;

        return reverse(ans);

    }
}